using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
using System.Drawing;
using LeisureCenter.Api;

namespace Aspire
{
    public class AspirePlugin : IPlugin
    {
        private AspireRemoteControl remoteControl;
        private AspireKnobControl knobControl;
        private AspireLcdDisplay lcdDisplay;
        internal IInstance leisureCenterInstance;
        internal SerialPort serialPort;

        private static byte[] ASPIRE_PC_MODE = new byte[] { 0x80 };

        internal void RestorePcMode()
        {
            if (this.serialPort != null)
                serialPort.Write(ASPIRE_PC_MODE, 0, 1);
        }

        #region IPlugin Membres

        public void Initialize(IInstance leisureCenterInstance)
        {
            this.leisureCenterInstance = leisureCenterInstance;
            remoteControl = new AspireRemoteControl(this);
            if (remoteControl.RemoteFound)
            {
                this.serialPort = new SerialPort("COM2");
                try
                {
                    this.serialPort.Open();
                    RestorePcMode();
                    this.knobControl = new AspireKnobControl(this);
                    this.lcdDisplay = new AspireLcdDisplay(this);
                }
                catch (UnauthorizedAccessException)
                {
                    leisureCenterInstance.UIManager.MessageBox(@"Could not access to the machine's front panel !", "error", MessageBoxButtons.OK, Color.Red);
                    this.serialPort.Dispose();
                    this.serialPort = null;
                }
            }
        }

        public void Finalize(IInstance leisureCenterInstance)
        {
            RestorePcMode();
            this.lcdDisplay = null;
            this.knobControl = null;
            if (this.remoteControl != null)
            {
                this.remoteControl.Dispose();
                this.remoteControl = null;
            }
            if (this.serialPort != null)
            {
                this.serialPort.Dispose();
                this.serialPort = null;
            }
        }

        #endregion
    }
}
